<template>
    <div class="wrap">
        <div class="close" @click="saveDraft">
            <el-icon :size="18" color="#000000">
                <CaretRight />
            </el-icon>
        </div>
        <div style="display: flex; align-items: center; justify-content: space-between; height: 30px;">
            <div class="title">创建工单</div>
        </div>
        <div class="content">
            <el-form ref="ruleFormRef" :model="info" :rules="rules">
                <div class="tit">基本信息</div>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="工单名称：" prop="title" style="display: flex; flex-direction: column;"
                            class="form_item">
                            <el-input v-model="info.title" placeholder="填写工单名称" style="width: 90%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工单类型：" prop="cate_id" style="display: flex; flex-direction: column;">
                            <!-- <el-cascader v-model="info.cate_id" :props="props" :options="cate" :show-all-levels="false"
                                style="width: 90%;" @change="handleChooseCate" /> -->
                            <el-select v-model="info.cate_id" placeholder="工单类型：" style="width: 90%"
                                @change="handleChooseCate">
                                <el-option v-for="item in cate" :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="对接人：" prop="docking_user" style="display: flex; flex-direction: column;">
                            <el-select v-model="info.docking_user" placeholder="选择对接人" style="width: 90%">
                                <el-option v-for="item in userList" :key="item.f_user_id" :label="item.user_name"
                                    :value="item.f_user_id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="对接方式：" prop="docking_type" style="display: flex; flex-direction: column;">
                            <el-select v-model="info.docking_type" placeholder="选择对接方式" style="width: 90%">
                                <el-option v-for="item in type" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="预计完成时间：" prop="plan_time" style="display: flex; flex-direction: column;">
                            <el-date-picker v-model="info.plan_time" type="datetime" placeholder="选择预计完成时间" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="tit" style="margin-top: 20px;">其它信息</div>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="其他要求及备注：" prop="remark" style="display: flex; flex-direction: column;">
                            <el-input v-model="info.remark" :rows="5" type="textarea" placeholder="请输入"
                                style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="聊天记录：" prop="chat_log" style="display: flex; flex-direction: column;">
                            <el-button type="primary" :disabled="mulitpleSelectStore.isOpen"
                                @click="handleSelectMsg">点击添加</el-button>
                            <div style="font-size: 12px; margin-left: 10px; padding: 0 10px; background-color: #eee; border-radius: 5px; cursor: pointer;"
                                @click="openSelectMsg" v-if="mulitpleSelectStore.selectList.length > 0">
                                当前选中<span style="color: #f00;">{{ mulitpleSelectStore.selectList.length
                                    }}条</span>聊天记录
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="其他文件：" prop="file" style="display: flex; flex-direction: column;">
                            <el-upload class="upload-demo" drag :action="uploadUrl" multiple :file-list="fileList"
                                :on-success="handleFileSuccess" style="display: flex;">
                                <el-icon class="el-icon--upload" size="40"><upload-filled /></el-icon>
                                <div style="font-size: 12px; line-height: 20px; color: #666;">
                                    点击或拖拽文件上传</br>文件不超过20M</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="footer">
            <el-button @click="cancelSubmit(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                提交
            </el-button>
        </div>
    </div>
    <el-dialog v-model="showMsgList" title="选中的聊天记录" width="700">
        <div style="height: calc(100vh - 300px); overflow-y: scroll;">
            <el-timeline style="max-width: 650px">
                <el-timeline-item :timestamp="formatTimestamp(item.clientTime)" placement="top"
                    v-for="(item, index) in mulitpleSelectStore.selectList" :key="index">
                    <el-card>
                        <h4
                            style="margin-bottom: 10px; color: #999; display: flex; align-items: center; justify-content: space-between;">
                            <span>{{ item.nick }}{{ item.from.includes('FW') ?
                                '（法务）' : (item.from == 'administrator' ? '' : '（客户）') }}</span>
                            <el-icon size="16" color="#666666" style="cursor: pointer;" @click="delMsg(index)">
                                <Delete />
                            </el-icon>
                        </h4>
                        <div v-if="item.type == 'TIMTextElem'">
                            <p>{{ item.payload.text }}</p>
                        </div>
                        <div v-if="item.type == 'TIMLocationElem'"></div>
                        <div v-if="item.type == 'TIMFaceElem'">【表情消息】</div>
                        <div v-if="item.type == 'TIMCustomElem'">
                            <div v-if="JSON.parse(item.payload.data).type == 'imgMsg'">
                                <div v-html="JSON.parse(item.payload.data).ext"></div>
                                <el-image style="width: 80px; height: 80px;"
                                    :src="JSON.parse(item.payload.data).imageUrl"
                                    :preview-src-list="[JSON.parse(item.payload.data).imageUrl]" fit="cover"
                                    v-if="JSON.parse(item.payload.data).imageUrl" />
                            </div>
                            <div v-if="JSON.parse(item.payload.data).type == 'evaluation'">【邀请评价】</div>
                        </div>
                        <div v-if="item.type == 'TIMSoundElem'"></div>
                        <div v-if="item.type == 'TIMImageElem'">
                            <template v-for="(itm, idx) in item.payload.imageInfoArray">
                                <el-image style="width: 80px; height: 80px;" :src="itm.imageUrl"
                                    :preview-src-list="[itm.imageUrl]" fit="cover" :key="idx" v-if="idx == 0" />
                            </template>
                        </div>
                        <div v-if="item.type == 'TIMFileElem'">
                            <a :href="item.payload.fileUrl" _blank="target">
                                <div style="display: flex; align-items: center;">
                                    <el-icon size="25" color="#666666">
                                        <FolderOpened />
                                    </el-icon>
                                    <span style="color: #409eff; margin-left: 5px;">{{ item.payload.fileName
                                        }}</span>
                                </div>
                            </a>
                        </div>
                        <div v-if="item.type == 'TIMVideoFileElem'"></div>
                        <div v-if="item.type == 'TIMRelayElem'"></div>
                    </el-card>
                </el-timeline-item>
            </el-timeline>
        </div>
    </el-dialog>
</template>
<script setup lang="ts">
import TUIChatEngine, {
    TUIChatService,
    SendMessageParams,
    SendMessageOptions,
    TUIStore,
    StoreName,
    IConversationModel,
} from '@tencentcloud/chat-uikit-engine';
import { reactive, ref, onMounted } from '../../../adapter-vue';
import { useSidebarStore } from '@/store/sidebar';
import { useMulitpleSelectStore } from '@/store/mulitpleSelect';
import { getWorkOrderCate, addWorkOrder, getWorkOrder, getGroupInfo, baseURL } from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { CascaderProps, UploadProps, FormInstance, Action } from 'element-plus'
import { formatTimestamp } from '@/utils/format'
const sidebarStore = useSidebarStore();
const mulitpleSelectStore = useMulitpleSelectStore();
const currentConversation = ref<IConversationModel>();
const uploadUrl = baseURL + '/admin/ajax/upload';
const info = ref({
    group_id: '',
    title: '',
    docking_user: '',
    docking_type: '',
    plan_time: '',
    remark: '',
    chat_log: '',
    file: '',
    cate_id: '',
    pid: '',
    status: 0
});
const cate = ref([{
    id: '',
    name: ''
}]);
const userList = ref([{
    f_user_id: 0,
    user_name: '',
}]);
const type = ref([{
    label: '法务群里沟通',
    value: 1
}, {
    label: '电联',
    value: 2
}, {
    label: '面谈',
    value: 3
}, {
    label: '客服、售前转交',
    value: 4
}]);
const showMsgList = ref(false)
const rules = ref({
    title: [{ required: true, message: '请填写工单名称', trigger: 'blur' }],
    cate_id: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
    docking_user: [{ required: true, message: '请选择对接人', trigger: 'change' }],
    docking_type: [{ required: true, message: '请选择对接类型', trigger: 'change' }],
    plan_time: [{ required: true, message: '请选择预计完成时间', trigger: 'change' }],
    remark: [{ required: true, message: '请填写特殊需求及备注', trigger: 'blur' }],
})
const props: CascaderProps = {
    lazy: true,
    value: 'id',
    label: 'name',
    lazyLoad(node, resolve) {
        const { level } = node;
        getWorkOrderCate({
            pid: node.value
        }).then(res => {
            const nodes = res.data.map((item: any) => ({
                id: item.id,
                name: item.name,
                leaf: level >= 1,
            }))
            resolve(nodes);
        });
    },
}
const ruleFormRef = ref<FormInstance>()
const fileList = ref([])
const groupId = ref('')

onMounted(() => {
    getWorkOrderCate({
        pid: 0
    }).then(res => {
        cate.value = res.data;
    });
});

sidebarStore.$subscribe((mutate, state) => {
    if (state.isOpen) {
        if (state.type == 'workOrder') {
            mulitpleSelectStore.setMulitpleSelect({
                isOpen: false,
                selectList: [],
                type: 1
            })
            getGroupInfo({
                GroupId: currentConversation?.value?.groupProfile?.groupID
            }).then(res => {
                groupId.value = res.data.GroupId;
                let list = res.data.member;
                userList.value = [];
                fileList.value = [];
                list.map((item: any) => {
                    if (item.user_type == 1) {
                        userList.value.push(item);
                    }
                })
                if (state.currentId) {
                    getWorkOrder({
                        id: state.currentId
                    }).then(res => {
                        if (res.data.docking_user) res.data.docking_user = res.data.docking_user.toString();
                        info.value = res.data;
                        mulitpleSelectStore.setMulitpleSelect({
                            isOpen: false,
                            selectList: res.data.chat_log ? JSON.parse(res.data.chat_log) : [],
                            type: 1
                        })
                        if(res.data.file){
                            let list = res.data.file.split(',')
                            list.map((item: any) => {
                                fileList.value.push({
                                    name: item,
                                    url: item
                                })
                            })
                        }
                    })
                } else {
                    info.value = {
                        group_id: '',
                        title: '',
                        docking_user: '',
                        docking_type: '',
                        plan_time: '',
                        remark: '',
                        chat_log: '',
                        file: '',
                        cate_id: '',
                        pid: '',
                        status: 0
                    }
                }
            })
        }
    } else {
        if (state.type == 'workOrder') {
            saveDraft()
        }
        resetForm(ruleFormRef.value)
    }
})

mulitpleSelectStore.$subscribe((mutate, state) => {
    if (state.selectList.length > 0) {
        info.value.chat_log = JSON.stringify(state.selectList)
    }
})

TUIStore.watch(StoreName.CONV, {
    currentConversation: (conversation: IConversationModel) => {
        currentConversation.value = conversation;
    },
});

function handleChooseCate(e: any) {
    // info.value.pid = e[0];
    // info.value.cate_id = e[1];
    const now = new Date();
    const newDate = formatTimestamp(now.setDate(now.getDate() + 2)/1000);
    info.value.plan_time = newDate;
}

function handleSelectMsg() {
    mulitpleSelectStore.setMulitpleSelect({
        isOpen: true,
        selectList: info.value.chat_log ? JSON.parse(info.value.chat_log) : [],
        type: 2
    });
}

const openSelectMsg = () => {
    showMsgList.value = true;
}

const handleFileSuccess: UploadProps['onSuccess'] = (
    response
) => {
    if (info.value.file) {
        info.value.file += ',' + response.data.url;
    } else {
        info.value.file = response.data.url;
    }
}

function closeSidebar() {
    resetForm(ruleFormRef.value)
    sidebarStore.setSidebar({
        isOpen: false,
        groupInfo: sidebarStore.groupInfo,
        type: sidebarStore.type,
        currentId: '',
    });
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            info.value.group_id = currentConversation?.value?.groupProfile?.groupID;
            info.value.status = 1;
            for (const key in info.value) {
                if (info.value.hasOwnProperty(key)) {
                    // Assert that info.value is indexable
                    const value = (info.value as Record<string, any>)[key];
                    if (value === null || value === undefined || value === '') {
                        delete info.value[key];
                    }
                }
            }
            addWorkOrder(info.value).then(res => {
                ElMessage({
                    message: '创建成功',
                    type: 'success',
                })
                closeSidebar()
            })
        } else {
            // console.log('error submit!', fields)
        }
    })
}

function cancelSubmit(){
    ElMessageBox.confirm(
        '是否确定取消本次编辑？',
        '操作提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '是',
            cancelButtonText: '否',
        }
    )
        .then((action: Action) => {
            if (action === 'confirm') {
                closeSidebar()
            }
        })
        .catch(() => {
            
        })
}

function saveDraft(){
    info.value.group_id = groupId.value;
    info.value.status = 0;
    for (const key in info.value) {
        if (info.value.hasOwnProperty(key)) {
            // Assert that info.value is indexable
            const value = (info.value as Record<string, any>)[key];
            if (value === null || value === undefined || value === '') {
                delete info.value[key];
            }
        }
    }
    if (info.value.title || info.value.docking_user || info.value.docking_type || info.value.plan_time || info.value.remark || info.value.chat_log || info.value.file || info.value.cate_id) {
        addWorkOrder(info.value).then(res => {
            closeSidebar()
            ElMessage({
                message: '保存草稿成功',
                type: 'success',
            })
        }).catch(err => {
            // ElMessage.error('保存失败，系统仅保留3份草稿')
            // ElMessageBox.confirm(
            //     '系统仅保留3份草稿，直接退出将丢失未提交工单，请选择操作',
            //     '操作提示',
            //     {
            //         distinguishCancelAndClose: true,
            //         confirmButtonText: '继续编辑',
            //         cancelButtonText: '退出',
            //     }
            // )
            //     .then(() => {
                    
            //     })
            //     .catch((action: Action) => {
            //         if (action === 'cancel') {
            //             closeSidebar()
            //         }
            //     })
        })
    } else {
        closeSidebar()
    }
}


const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
<style lang="scss" scoped>
.wrap {
    padding: 20px 20px 10px;
    position: relative;

    .close {
            position: absolute;
            top: 45%;
            left: 7px;
            background-color: #d6d6d6;
            border-radius: 0 6px 6px 0;
            margin-top: -10px;
            width: 12px;
            height: 44px;
            background-size: cover;
            background-position: center;
            font-size: 32px;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

    .title {
        font-size: 18px;
        font-weight: bold;
        color: #333333;
    }

    .content {
        padding: 20px 0 0;
        height: calc(100vh - 120px);
        overflow-y: auto;

        .tit {
            font-size: 16px;
            margin-bottom: 20px;
        }
    }

    .footer {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 49px;
        border-top: 1px solid #f4f5f9;
    }

    :deep(.el-form-item__label) {
        justify-content: flex-start !important;
    }

}
</style>